// NBA相关数据模型
import 'package:flutter/material.dart';
import 'dart:convert';

// 赛事类型枚举
enum SportType {
  all('全部', 0),
  basketball('篮球', 0),
  football('足球', 0),
  lol('英雄联盟', 0),
  csgo('CS.GO', 0),
  dota2('DOTA2', 0),
  kog('王者荣耀', 0);
  
  final String name;
  final int eventId;
  
  const SportType(this.name, this.eventId);
}
/// NBA比赛直播信息
class NbaLiveMatch {
  final String id;
  final String homeTeam;
  final String awayTeam;
  final String homeLogo;
  final String awayLogo;
  final String matchTime;
  final String league;
  final String status; // 未开始、进行中、已结束
  final String score;
  final List<NbaLiveSource> liveSources;
  final String? highlightUrl; // 集锦链接

  NbaLiveMatch({
    required this.id,
    required this.homeTeam,
    required this.awayTeam,
    required this.homeLogo,
    required this.awayLogo,
    required this.matchTime,
    required this.league,
    required this.status,
    required this.score,
    required this.liveSources,
    this.highlightUrl,
  });

  factory NbaLiveMatch.fromJson(Map<String, dynamic> json) {
    return NbaLiveMatch(
      id: json['id']?.toString() ?? '',
      homeTeam: json['homeTeam']?.toString() ?? '',
      awayTeam: json['awayTeam']?.toString() ?? '',
      homeLogo: json['homeLogo']?.toString() ?? '',
      awayLogo: json['awayLogo']?.toString() ?? '',
      matchTime: json['matchTime']?.toString() ?? '',
      league: json['league']?.toString() ?? '',
      status: json['status']?.toString() ?? '未开始',
      score: json['score']?.toString() ?? '0-0',
      liveSources: (json['liveSources'] as List? ?? [])
          .map((e) => NbaLiveSource.fromJson(e))
          .toList(),
      highlightUrl: json['highlightUrl']?.toString(),
    );
  }
}

/// NBA新闻详情内容属性
class NbaNewsContentAttribute {
  final int itype; // 1: 文本, 2: 图片, 3: 视频
  final String placeholder;
  final String newsId;
  final Map<String, dynamic> user;
  final Map<String, dynamic> object;

  NbaNewsContentAttribute({
    required this.itype,
    required this.placeholder,
    required this.newsId,
    required this.user,
    required this.object,
  });

  factory NbaNewsContentAttribute.fromJson(Map<String, dynamic> json) {
   final object = json['object'] as String;
   // 先去除转义字符，然后解析 JSON
   final cleanedObject = object.replaceAll('\"', '"').replaceAll('\\\\', '\\');
   final objectJson = jsonDecode(cleanedObject);
    return NbaNewsContentAttribute(
      itype: json['itype'] ?? 1,
      placeholder: json['placeholder']?.toString() ?? '',
      newsId: json['news_id']?.toString() ?? '',
      user: json['user'] is Map ? Map<String, dynamic>.from(json['user']) : {},
      object: objectJson,
    );
  }
}

/// NBA新闻详情信息
class NbaNewsDetail {
  final int id;
  final String newsId;
  final String title;
  final String thumbnail;
  final String thumbnail2x;
  final String thumbnailY;
  final String thumbnailY2x;
  final String abstractText;
  final DateTime publishTime;
  final int atype;
  final String editor;
  final String source;
  final String columnTag;
  final int tagId;
  final int cid;
  final String contentHtml;
  final List<NbaNewsContentAttribute> contentAttributes;

  NbaNewsDetail({
    required this.id,
    required this.newsId,
    required this.title,
    required this.thumbnail,
    required this.thumbnail2x,
    required this.thumbnailY,
    required this.thumbnailY2x,
    required this.abstractText,
    required this.publishTime,
    required this.atype,
    required this.editor,
    required this.source,
    required this.columnTag,
    required this.tagId,
    required this.cid,
    required this.contentHtml,
    required this.contentAttributes,
  });

  factory NbaNewsDetail.fromJson(Map<String, dynamic> json) {
    return NbaNewsDetail(
      id: json['id'] ?? 0,
      newsId: json['news_id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      thumbnail: json['thumbnail']?.toString() ?? '',
      thumbnail2x: json['thumbnail_2x']?.toString() ?? '',
      thumbnailY: json['thumbnail_y']?.toString() ?? '',
      thumbnailY2x: json['thumbnail_y_2x']?.toString() ?? '',
      abstractText: json['abstract']?.toString() ?? '',
      publishTime: DateTime.parse(json['publish_time']?.toString() ?? DateTime.now().toString()),
      atype: json['atype'] ?? 0,
      editor: json['editor']?.toString() ?? '',
      source: json['source']?.toString() ?? '',
      columnTag: json['column_tag']?.toString() ?? '',
      tagId: json['TagID'] ?? 0,
      cid: json['Cid'] ?? 0,
      contentHtml: json['cnt_html']?.toString() ?? '',
      contentAttributes: (json['cnt_attr'] as List? ?? [])
          .map((attr) => NbaNewsContentAttribute.fromJson(attr))
          .toList(),
    );
  }

  /// 获取最佳缩略图URL
  String get bestThumbnailUrl {
    if (thumbnail2x.isNotEmpty) return thumbnail2x;
    if (thumbnailY2x.isNotEmpty) return thumbnailY2x;
    if (thumbnail.isNotEmpty) return thumbnail;
    if (thumbnailY.isNotEmpty) return thumbnailY;
    return '';
  }

  /// 获取格式化发布时间
  String get formattedPublishTime {
    return '${publishTime.year}年${publishTime.month}月${publishTime.day}日 ${publishTime.hour.toString().padLeft(2, '0')}:${publishTime.minute.toString().padLeft(2, '0')}';
  }
}
/// NBA直播源
class NbaLiveSource {
  final String name;
  final String url;
  final String quality;
  final String source; // 来源：jrs、24zb等
  final String? type;
  final bool isFree;

  NbaLiveSource({
    required this.name,
    required this.url,
    required this.quality,
    required this.source,
    required this.type,
    this.isFree = true,
  });

  factory NbaLiveSource.fromJson(Map<String, dynamic> json) {
    return NbaLiveSource(
      name: json['name']?.toString() ?? '',
      url: json['url']?.toString() ?? '',
      quality: json['quality']?.toString() ?? '高清',
      source: json['source']?.toString() ?? '',
      type: json['type']?.toString(),
      isFree: json['isFree'] ?? true,
    );
  }
}

/// NBA新闻资讯
class NbaNews {
  final String id;
  final String title;
  final String summary;
  final String imageUrl;
  final String source; // 来源：虎扑、腾讯等
  final DateTime publishTime;
  final String url;
  final int commentCount;
  final int likeCount;

  NbaNews({
    required this.id,
    required this.title,
    required this.summary,
    required this.imageUrl,
    required this.source,
    required this.publishTime,
    required this.url,
    required this.commentCount,
    required this.likeCount,
  });

  factory NbaNews.fromJson(Map<String, dynamic> json) {
    return NbaNews(
      id: json['id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      summary: json['summary']?.toString() ?? '',
      imageUrl: json['imageUrl']?.toString() ?? '',
      source: json['source']?.toString() ?? '虎扑',
      publishTime: DateTime.parse(json['publishTime']?.toString() ?? DateTime.now().toString()),
      url: json['url']?.toString() ?? '',
      commentCount: json['commentCount'] ?? 0,
      likeCount: json['likeCount'] ?? 0,
    );
  }
}

/// NBA集锦视频
class NbaHighlight {
  final String id;
  final String title;
  final String thumbnail;
  final String duration;
  final DateTime publishTime;
  final String videoUrl;
  final String source;
  final int viewCount;

  NbaHighlight({
    required this.id,
    required this.title,
    required this.thumbnail,
    required this.duration,
    required this.publishTime,
    required this.videoUrl,
    required this.source,
    required this.viewCount,
  });

  factory NbaHighlight.fromJson(Map<String, dynamic> json) {
    return NbaHighlight(
      id: json['id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      thumbnail: json['thumbnail']?.toString() ?? '',
      duration: json['duration']?.toString() ?? '00:00',
      publishTime: DateTime.parse(json['publishTime']?.toString() ?? DateTime.now().toString()),
      videoUrl: json['videoUrl']?.toString() ?? '',
      source: json['source']?.toString() ?? '',
      viewCount: json['viewCount'] ?? 0,
    );
  }
}

/// NBA纪录片
class NbaDocumentary {
  final String id;
  final String title;
  final String cover;
  final String description;
  final String videoUrl;
  final String duration;
  final DateTime releaseDate;
  final String director;
  final List<String> tags;
  final double rating;

  NbaDocumentary({
    required this.id,
    required this.title,
    required this.cover,
    required this.description,
    required this.videoUrl,
    required this.duration,
    required this.releaseDate,
    required this.director,
    required this.tags,
    required this.rating,
  });

  factory NbaDocumentary.fromJson(Map<String, dynamic> json) {
    return NbaDocumentary(
      id: json['id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      cover: json['cover']?.toString() ?? '',
      description: json['description']?.toString() ?? '',
      videoUrl: json['videoUrl']?.toString() ?? '',
      duration: json['duration']?.toString() ?? '',
      releaseDate: DateTime.parse(json['releaseDate']?.toString() ?? DateTime.now().toString()),
      director: json['director']?.toString() ?? '',
      tags: List<String>.from(json['tags'] ?? []),
      rating: (json['rating'] ?? 0.0).toDouble(),
    );
  }
}

/// NBA球队信息
class NbaTeam {
  final String id;
  final String name;
  final String logo;
  final String conference;
  final String division;
  final int wins;
  final int losses;
  final double winPercentage;
  final String city;

  NbaTeam({
    required this.id,
    required this.name,
    required this.logo,
    required this.conference,
    required this.division,
    required this.wins,
    required this.losses,
    required this.winPercentage,
    required this.city,
  });

  factory NbaTeam.fromJson(Map<String, dynamic> json) {
    return NbaTeam(
      id: json['id']?.toString() ?? '',
      name: json['name']?.toString() ?? '',
      logo: json['logo']?.toString() ?? '',
      conference: json['conference']?.toString() ?? '',
      division: json['division']?.toString() ?? '',
      wins: json['wins'] ?? 0,
      losses: json['losses'] ?? 0,
      winPercentage: (json['winPercentage'] ?? 0.0).toDouble(),
      city: json['city']?.toString() ?? '',
    );
  }
}

/// NBA球员信息
class NbaPlayer {
  final String id;
  final String name;
  final String team;
  final String position;
  final String avatar;
  final int jerseyNumber;
  final double points;
  final double rebounds;
  final double assists;
  final double blocks;
  final double steals;

  NbaPlayer({
    required this.id,
    required this.name,
    required this.team,
    required this.position,
    required this.avatar,
    required this.jerseyNumber,
    required this.points,
    required this.rebounds,
    required this.assists,
    required this.blocks,
    required this.steals,
  });

  factory NbaPlayer.fromJson(Map<String, dynamic> json) {
    return NbaPlayer(
      id: json['id']?.toString() ?? '',
      name: json['name']?.toString() ?? '',
      team: json['team']?.toString() ?? '',
      position: json['position']?.toString() ?? '',
      avatar: json['avatar']?.toString() ?? '',
      jerseyNumber: json['jerseyNumber'] ?? 0,
      points: (json['points'] ?? 0.0).toDouble(),
      rebounds: (json['rebounds'] ?? 0.0).toDouble(),
      assists: (json['assists'] ?? 0.0).toDouble(),
      blocks: (json['blocks'] ?? 0.0).toDouble(),
      steals: (json['steals'] ?? 0.0).toDouble(),
    );
  }
}

// 数据源解析工具类
class NbaDataSourceParser {
  
  /// 从虎扑体育数据解析NBA比赛
  static List<NbaLiveMatch> parseHupuMatches(String responseBody) {
    try {
      final json = jsonDecode(responseBody);
      final List<dynamic> matches = json['result']?['matches'] ?? [];
      return matches.map((match) {
        return NbaLiveMatch(
          id: match['id']?.toString() ?? '',
          homeTeam: match['home_team']?['name']?.toString() ?? '',
          awayTeam: match['away_team']?['name']?.toString() ?? '',
          homeLogo: match['home_team']?['logo']?.toString() ?? '',
          awayLogo: match['away_team']?['logo']?.toString() ?? '',
          matchTime: match['start_time']?.toString() ?? '',
          league: match['league']?['name']?.toString() ?? 'NBA',
          status: _parseMatchStatus(match['status']),
          score: '${match['home_score'] ?? 0}-${match['away_score'] ?? 0}',
          liveSources: _parseHupaLiveSources(match['live_sources']),
          highlightUrl: match['highlight_url']?.toString(),
        );
      }).toList();
    } catch (e) {
      return [];
    }
  }

  /// 从JRS直播数据解析直播源
  static List<NbaLiveMatch> parseJrsMatches(String responseBody) {
    try {
      final json = jsonDecode(responseBody);
      final List<dynamic> matches = json['data'] ?? [];
      return matches.map((match) {
        return NbaLiveMatch(
          id: match['id']?.toString() ?? '',
          homeTeam: match['home']?.toString() ?? '',
          awayTeam: match['away']?.toString() ?? '',
          homeLogo: match['home_logo']?.toString() ?? '',
          awayLogo: match['away_logo']?.toString() ?? '',
          matchTime: match['time']?.toString() ?? '',
          league: 'NBA',
          status: _parseMatchStatus(match['state']),
          score: match['score']?.toString() ?? '0-0',
          liveSources: _parseJrsLiveSources(match['links']),
        );
      }).toList();
    } catch (e) {
      return [];
    }
  }

  /// 从24小时直播数据解析比赛
  static List<NbaLiveMatch> parseShuoqiudiMatches(String responseBody) {
    try {
      final json = jsonDecode(responseBody);
      final List<dynamic> matches = json['list'] ?? [];
      return matches.map((match) {
        return NbaLiveMatch(
          id: match['id']?.toString() ?? '',
          homeTeam: match['team1']?.toString() ?? '',
          awayTeam: match['team2']?.toString() ?? '',
          homeLogo: match['team1_logo']?.toString() ?? '',
          awayLogo: match['team2_logo']?.toString() ?? '',
          matchTime: match['start_time']?.toString() ?? '',
          league: 'NBA',
          status: _parseMatchStatus(match['status']),
          score: match['score']?.toString() ?? '0-0',
          liveSources: _parse24zbLiveSources(match['live_urls']),
        );
      }).toList();
    } catch (e) {
      return [];
    }
  }

  /// 从虎扑体育解析新闻
  static List<NbaNews> parseHupuNews(String responseBody) {
    try {
      final json = jsonDecode(responseBody);
      final List<dynamic> newsList = json['result']?['list'] ?? [];
      return newsList.map((news) {
        return NbaNews(
          id: news['id']?.toString() ?? '',
          title: news['title']?.toString() ?? '',
          summary: news['summary']?.toString() ?? '',
          imageUrl: news['img']?.toString() ?? '',
          source: '虎扑',
          publishTime: DateTime.parse(news['publish_time']?.toString() ?? DateTime.now().toString()),
          url: news['url']?.toString() ?? '',
          commentCount: news['reply_count'] ?? 0,
          likeCount: news['like_count'] ?? 0,
        );
      }).toList();
    } catch (e) {
      return [];
    }
  }

  /// 解析比赛状态
  static String _parseMatchStatus(dynamic status) {
    if (status == null) return '未开始';
    if (status is int) {
      if (status == 0) return '未开始';
      if (status == 1) return '进行中';
      if (status == 2) return '已结束';
    }
    if (status is String) {
      if (status.contains('未开始')) return '未开始';
      if (status.contains('进行中') || status.contains('直播中')) return '进行中';
      if (status.contains('已结束') || status.contains('完场')) return '已结束';
    }
    return status.toString();
  }

  /// 解析虎扑直播源
  static List<NbaLiveSource> _parseHupaLiveSources(dynamic sources) {
    if (sources == null) return [];
    final List<NbaLiveSource> result = [];
    if (sources is List) {
      for (var source in sources) {
        result.add(NbaLiveSource(
          name: source['name']?.toString() ?? '虎扑直播',
          url: source['url']?.toString() ?? '',
          quality: source['quality']?.toString() ?? '高清',
          source: 'hupu',
          type: source['type']?.toString(),
          isFree: source['is_free'] ?? true,
        ));
      }
    }
    return result;
  }

  /// 解析JRS直播源
  static List<NbaLiveSource> _parseJrsLiveSources(dynamic links) {
    if (links == null) return [];
    final List<NbaLiveSource> result = [];
    if (links is Map) {
      links.forEach((key, value) {
        if (value is String && value.isNotEmpty) {
          result.add(NbaLiveSource(
            name: 'JRS直播 - ${key}',
            url: value,
            quality: '高清',
            source: 'jrs',
            type: '',
            isFree: true,
          ));
        }
      });
    }
    return result;
  }

  /// 解析24小时直播源
  static List<NbaLiveSource> _parse24zbLiveSources(dynamic urls) {
    if (urls == null) return [];
    final List<NbaLiveSource> result = [];
    if (urls is List) {
      for (var url in urls) {
        if (url is String && url.isNotEmpty) {
          result.add(NbaLiveSource(
            name: '24小时直播',
            url: url,
            quality: '高清',
            source: '24zb',
            type: '',
            isFree: true,
          ));
        }
      }
    }
    return result;
  }

  /// 解析NBA中国官网赛程数据
  static List<NbaSchedule> parseNbaCnSchedules(String responseBody) {
    try {
      final json = jsonDecode(responseBody);
      
      // 检查API响应状态
      if (json['code'] != 0) {
        print('NBA中国官网赛程API错误: ${json['msg']}');
        return [];
      }
      
      final data = json['data'];
      if (data == null) return [];
      
      final List<NbaSchedule> schedules = [];
      
      // 解析新的API格式 - 包含groups数组
      final List<dynamic> groups = data['groups'] ?? [];
      
      for (var group in groups) {
        final List<dynamic> games = group['games'] ?? [];
        
        for (var game in games) {
          // 解析比赛状态
          final statusText = game['statusText']?.toString() ?? '未开始';
          
          // 解析比分信息
          String? score;
          final homeScore = game['homeTeamScore'] ?? 0;
          final awayScore = game['awayTeamScore'] ?? 0;
          
          score = '$homeScore-$awayScore';

          // 解析比赛时间（已经是东八区时间格式）
          DateTime matchTime;
          try {
            matchTime = DateTime.parse(game['dateTimeUtc']);
            matchTime = matchTime.add(Duration(hours: 16));
          } catch (e) {
            print('解析比赛时间失败: $e');
            matchTime = DateTime.now();
          }          
          schedules.add(NbaSchedule(
            id: game['gameId']?.toString() ?? '',
            homeTeam: game['homeTeamName']?.toString() ?? '',
            awayTeam: game['awayTeamName']?.toString() ?? '',
            homeLogo: game['homeTeamLogoLight']?.toString() ?? '',
            awayLogo: game['awayTeamLogoLight']?.toString() ?? '',
            matchTime: matchTime,
            league: game['seasonName']?.toString() ?? 'NBA',
            status: statusText,
            score: score,
            venue: game['arenaName']?.toString() ?? '',
            quarter: game['periodText']?.toString(),
            gameClock: game['gameClock']?.toString(),
            seasonName: game['seasonName']?.toString(),
            homeScore: homeScore.toString(),
            awayScore: awayScore.toString(),
            broadcast: '', // 新格式中暂无转播信息
          ));
        }
      }
      
      return schedules;
    } catch (e) {
      print('解析NBA中国官网赛程失败: $e');
      return [];
    }
  }
  
  /// 解析NBA中国官网比赛状态
  static String _parseNbaCnMatchStatus(dynamic status) {
    if (status == null) return '未开始';
    if (status is int) {
      switch (status) {
        case 0: return '未开始';
        case 1: return '进行中';
        case 2: return '已结束';
        case 3: return '延期';
        case 4: return '取消';
        default: return '未开始';
      }
    }
    return status.toString();
  }
  
  /// 解析NBA中国官网转播信息
  static String _parseNbaCnBroadcast(dynamic broadcastInfo) {
    if (broadcastInfo == null) return '';
    
    if (broadcastInfo is List) {
      final broadcastList = broadcastInfo.map((info) {
        if (info is Map) {
          return info['broadcast_name']?.toString() ?? '';
        }
        return '';
      }).where((name) => name.isNotEmpty).toList();
      
      return broadcastList.join(', ');
    }
    
    return '';
  }

  /// 解析NBA中国官网集锦视频数据
  static List<NbaHighlight> parseNbaCnHighlights(String responseBody) {
    try {
      final json = jsonDecode(responseBody);
      // 检查API响应状态
      if (json['code'] != 0) {
        print('NBA中国官网集锦API错误: ${json['msg']}');
        return [];
      }
      
      final List<dynamic> data = json['data'] ?? [];
      if (data.isEmpty) return [];
      
      final List<NbaHighlight> highlights = [];
      
      // 遍历数据列表，查找包含contents的模块
      for (var module in data) {
        if (module is Map && module['contents'] is List) {
          final List<dynamic> contents = module['contents'] ?? [];
          
          for (var content in contents) {
            try {
              // 获取文章信息
              final article = content['article'] ?? {};
              if (article['atype'] != 3) continue; // 只处理视频类型（atype=3）
              
              // 解析视频信息
              final String videoId = article['column_tag']?.toString() ?? '';
              final String title = article['title']?.toString() ?? '';
              
              // 获取缩略图，优先使用横版缩略图
              String thumbnail = article['thumbnail']?.toString() ?? '';
              if (thumbnail.isEmpty) {
                thumbnail = article['thumbnail_2x']?.toString() ?? '';
              }
              if (thumbnail.isEmpty) {
                thumbnail = article['thumbnail_y']?.toString() ?? '';
              }
              if (thumbnail.isEmpty) {
                thumbnail = article['thumbnail_y_2x']?.toString() ?? '';
              }
              
              // 解析时长（秒转分钟:秒格式）
              final int durationSeconds = article['duration'] ?? 0;
              final String duration = '${(durationSeconds ~/ 60).toString().padLeft(2, '0')}:${(durationSeconds % 60).toString().padLeft(2, '0')}';
              
              // 解析发布时间
              DateTime publishTime;
              try {
                publishTime = DateTime.parse(article['publish_time']?.toString() ?? DateTime.now().toString());
              } catch (e) {
                publishTime = DateTime.now();
              }
              
              // 获取观看次数
              final int viewCount = article['view_count'] ?? 0;
              
              // 构建视频URL（需要调用详情API获取真实播放地址）
              final String videoUrl = 'https://api.nba.cn/cms/v1/video/playurl?vid=$videoId';
              
              highlights.add(NbaHighlight(
                id: videoId,
                title: title,
                thumbnail: thumbnail,
                duration: duration,
                publishTime: publishTime,
                videoUrl: videoUrl,
                source: 'NBA中国',
                viewCount: viewCount,
              ));
            } catch (e) {
              print('解析单个集锦视频失败: $e');
            }
          }
        }
      }
      
      return highlights;
    } catch (e) {
      print('解析NBA中国官网集锦失败: $e');
      return [];
    }
  }

  /// 从看球吧数据解析NBA比赛
  static List<NbaLiveMatch> parseKanqiubaMatches(String responseBody) {
    try {
      final json = jsonDecode(responseBody);
      
      // 检查API响应状态
      if (json['status'] != 0) {
        print('看球吧API错误: ${json['message'] ?? '未知错误'}');
        return [];
      }
      
      final data = json['data'];
      if (data == null) return [];
      
      final List<dynamic> matches = data['matchs'] ?? [];
      
      return matches.map((match) {
        // 解析比赛状态
        final int status = match['status'] ?? 0;
        final String statusText = _parseKanqiubaMatchStatus(status);
        
        // 解析比分
        final int homeScore = match['home_score'] ?? 0;
        final int awayScore = match['away_score'] ?? 0;
        final String score = statusText == '未开始' ? '0-0' : '$homeScore-$awayScore';
        
        // 解析比赛时间（时间戳转DateTime）
        final int timestamp = match['time'] ?? 0;
        DateTime matchTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
        // 去除毫秒，仅保留到秒
        final String matchTimeNoMillis = matchTime.toString().split('.').first;
        
        // 解析球队信息
        final homeTeam = match['hometeam']?['name_zh']?.toString() ?? '';
        final awayTeam = match['awayteam']?['name_zh']?.toString() ?? '';
        final homeLogo = match['hometeam']?['logo']?.toString() ?? '';
        final awayLogo = match['awayteam']?['logo']?.toString() ?? '';
        
        // 解析联赛信息
        final league = match['matchevent']?['name_zh']?.toString() ?? 'NBA';
        
        // 解析直播源（看球吧的直播源信息在walematch中）
        final walematch = match['walematch'];
        final List<NbaLiveSource> liveSources = _parseKanqiubaLiveSources(walematch);
        
        return NbaLiveMatch(
          id: match['id']?.toString() ?? '',
          homeTeam: homeTeam,
          awayTeam: awayTeam,
          homeLogo: homeLogo,
          awayLogo: awayLogo,
          matchTime: matchTimeNoMillis,
          league: league,
          status: statusText,
          score: score,
          liveSources: liveSources,
        );
      }).toList();
    } catch (e) {
      print('解析看球吧比赛数据失败: $e');
      return [];
    }
  }

  /// 解析看球吧比赛状态
  static String _parseKanqiubaMatchStatus(int status) {
    switch (status) {
      case 0: // 未开始
      case 9: // 未开始（另一种状态）
        return '未开始';
      case 1: // 上半场
        return '未开始';
      case 2: // 中场
      case 3: // 下半场
      case 4: // 加时
      case 5: // 点球
      case 6: // 中断
      case 7: // 暂停
        return '进行中';
      case 8: // 已结束
      case -1: // 已结束
      case 10: // 取消
      case 11: // 延期
        return '已结束';
      default:
        return '未开始';
    }
  }

  /// 解析NBA中国官网新闻数据
  static List<NbaNews> parseNbaCnNews(String responseBody) {
    try {
      final json = jsonDecode(responseBody);
      // 检查API响应状态
      if (json['code'] != 0) {
        print('NBA中国官网新闻API错误: ${json['msg']}');
        return [];
      }
      
      final data = json['data'];
      if (data == null) return [];
      return data.map<NbaNews>((news) {
        // 使用缩略图作为图片URL，优先使用横版缩略图
        String imageUrl = news['thumbnail']?.toString() ?? '';
        if (imageUrl.isEmpty) {
          imageUrl = news['thumbnail_2x']?.toString() ?? '';
        }
        if (imageUrl.isEmpty) {
          imageUrl = news['thumbnail_y']?.toString() ?? '';
        }
        if (imageUrl.isEmpty) {
          imageUrl = news['thumbnail_y_2x']?.toString() ?? '';
        }
        // 使用abstract作为summary，如果为空则使用abstract_pad
        String summary = news['abstract']?.toString() ?? '';
        if (summary.isEmpty) {
          summary = news['abstract_pad']?.toString() ?? '';
        }
        final url=""; 
        final commentCount=0; //评论
        final likeCount=0; //点赞
        final source="NBA中国";
        return NbaNews(
          id: news['news_id']?.toString() ?? '',
          title: news['title']?.toString() ?? '',
          summary: summary,
          imageUrl: imageUrl,
          source: source,
          publishTime: DateTime.parse(news['publish_time']?.toString() ?? DateTime.now().toString()),
          url: url,
          commentCount: commentCount,
          likeCount: likeCount,
        );
      }).toList();
    } catch (e) {
      print('解析NBA中国官网新闻失败: $e');
      return [];
    }
  }

  /// 解析看球吧直播源
  static List<NbaLiveSource> _parseKanqiubaLiveSources(dynamic walematch) {
    if (walematch == null || walematch is! Map) return [];
    
    final List<NbaLiveSource> result = [];
    
    // 检查是否有直播流
    final walematchstreams = walematch['walematchstreams'];
    if (walematchstreams is List && walematchstreams.isNotEmpty) {
      for (var stream in walematchstreams) {
        if (stream is Map) {
          final streamUrl = stream['record_url']?.toString() ?? '';
          if (streamUrl.isNotEmpty) {
            result.add(NbaLiveSource(
              name: '回放',
              url: streamUrl,
              quality: '高清',
              source: 'kanqiuba',
              type: stream['type']?.toString(),
              isFree: true,
            ));
          }
        }
      }
    }
    
    // 检查是否有视频源
    final walematchvideos = walematch['walematchvideos'];
    if (walematchvideos is List && walematchvideos.isNotEmpty) {
      for (var video in walematchvideos) {
        if (video is Map) {
          final videoUrl = video['video_url']?.toString() ?? '';
          if (videoUrl.isNotEmpty) {
            result.add(NbaLiveSource(
              name: '视频源${video['id']?.toString() ?? ''}',
              url: videoUrl,
              quality: '高清',
              source: 'kanqiuba',
              type: video['type']?.toString(),
              isFree: true,
            ));
          }
        }
      }
    }
    
    return result;
  }
}

/// NBA赛程信息
class NbaSchedule {
  final String id;
  final String homeTeam;
  final String awayTeam;
  final String homeLogo;
  final String awayLogo;
  final DateTime matchTime;
  final String league;
  final String status; // 未开始、进行中、已结束
  final String? score;
  final String? quarter; // 第几节（如：Q1、Q2、Q3、Q4、OT等）
  final String? gameClock; // 比赛剩余时间
  final String? homeScore; // 主队实时比分
  final String? awayScore; // 客队实时比分
  final String? seasonName;
  final String venue; // 比赛场馆
  final String broadcast; // 转播信息

  NbaSchedule({
    required this.id,
    required this.homeTeam,
    required this.awayTeam,
    required this.homeLogo,
    required this.awayLogo,
    required this.matchTime,
    required this.league,
    required this.status,
    this.score,
    this.quarter,
    this.gameClock,
    this.homeScore,
    this.awayScore,
    this.seasonName,
    required this.venue,
    required this.broadcast,
  });

  factory NbaSchedule.fromJson(Map<String, dynamic> json) {
    return NbaSchedule(
      id: json['id']?.toString() ?? '',
      homeTeam: json['homeTeam']?.toString() ?? '',
      awayTeam: json['awayTeam']?.toString() ?? '',
      homeLogo: json['homeLogo']?.toString() ?? '',
      awayLogo: json['awayLogo']?.toString() ?? '',
      matchTime: DateTime.parse(json['matchTime']?.toString() ?? DateTime.now().toString()),
      league: json['league']?.toString() ?? 'NBA',
      status: json['status']?.toString() ?? '未开始',
      score: json['score']?.toString(),
      quarter: json['quarter']?.toString(),
      gameClock: json['gameClock']?.toString(),
      homeScore: json['homeScore']?.toString(),
      awayScore: json['awayScore']?.toString(),
      seasonName: json['seasonName']?.toString(),
      venue: json['venue']?.toString() ?? '',
      broadcast: json['broadcast']?.toString() ?? '',
    );
  }
}

/// NBA赛程响应
class NbaScheduleResponse {
  final int code;
  final String message;
  final List<NbaSchedule> schedules;
  final int total;

  NbaScheduleResponse({
    required this.code,
    required this.message,
    required this.schedules,
    required this.total,
  });

  factory NbaScheduleResponse.fromJson(Map<String, dynamic> json) {
    return NbaScheduleResponse(
      code: json['code'] ?? 0,
      message: json['msg']?.toString() ?? '',
      schedules: (json['data']?['list'] as List? ?? [])
          .map((e) => NbaSchedule.fromJson(e))
          .toList(),
      total: json['data']?['total'] ?? 0,
    );
  }
}